
package nccloud.rongq.bill.centervo.action;

import java.util.Collection;

import org.apache.commons.lang3.StringUtils;

import nc.bs.logging.Logger;
import nc.itf.uap.IUAPQueryBS;
import nc.jdbc.framework.processor.ColumnProcessor;
import nc.vo.pub.BusinessException;
import nc.vo.pub.CircularlyAccessibleValueObject;
import nc.vo.pub.lang.UFDate;
import nc.vo.rongq.lrcenter.AggCenterVO;
import nc.vo.rongq.lrcenter.CenterBVO;
import nc.vo.rongq.lrcenter.CenterVO;
import nccloud.framework.core.exception.ExceptionUtils;
import nccloud.framework.service.ServiceLocator;
import nccloud.framework.web.action.itf.ICommonAction;
import nccloud.framework.web.container.IRequest;
import nccloud.framework.web.ui.pattern.billcard.BillCardOperator;
import nccloud.pubitf.riart.pflow.CloudPFlowContext;
import nccloud.pubitf.riart.pflow.ICloudScriptPFlowService;
import nccloud.rongq.bill.centervo.bill.util.CommonUtil;
import nccloud.vo.rongq.bill.CenterVOConst;

/**
 * 主子表保存
 * @version  @since v3.5.6-1903
 */
public class CenterVOSaveAction implements ICommonAction {

  @Override
  public Object doAction(IRequest paramIRequest) {
    try {
      BillCardOperator billCardOperator = new BillCardOperator();
      // 1、获取AGGVO （request转换主子VO）
AggCenterVO vo = billCardOperator.toBill(paramIRequest);
      this.doBefore(vo);
      // 2、调用单据的保存动作脚本（savebase），得到保存后结果
AggCenterVO rtnObj = this.callActionScript(vo);
      // 3、处理返回结果（包含功能：根据模板转换前端BillCard，参照翻译，显示公式处理）
      Object billcard = billCardOperator.toCard(rtnObj);
      // 4、返回结果到前端
      return billcard;
    }
    catch (BusinessException ex) {
      // 处理异常信息
      Logger.error(ex);
      ExceptionUtils.wrapException(ex);
    }
    return null;
  }

  /**
   * 动作编码
   *
   * @return
   */
  protected String getActionCode() {
    return CenterVOConst.CONST_ACTION_SAVEBASE;
  }

  /**
   * 调用动作脚本
   *
   * @param actionCode
   * @param aggVOs
   * @return
   * @throws BusinessException
   */
  private AggCenterVO callActionScript(AggCenterVO... aggVOs)
      throws BusinessException {

    String actionCode = this.getActionCode();
    String billType = CenterVOConst.CONST_BILLTYPE_COST;

    CloudPFlowContext context = new CloudPFlowContext();
    context.setActionName(actionCode);
    context.setBillType(billType);
    context.setBillVos(aggVOs);
    Logger.debug("开始调用动作脚本 ActionName[" + actionCode + "] BillType[" + billType
        + "]...");

    ICloudScriptPFlowService service =
        CommonUtil.getCloudScriptPFlowService();

    Object[] result = service.exeScriptPFlow(context);

    Logger.debug("调用动作脚本 ActionName[" + actionCode + "] BillType[" + billType
        + "]结束");

    String wheresql =
        "pk_lrcenter_h" + "='"
            + ((AggCenterVO) result[0]).getPrimaryKey() + "'";
    Collection<AggCenterVO> bills =
        CommonUtil.getMDPersistenceQueryService().queryBillOfVOByCond(
            AggCenterVO.class, wheresql, true, false);
    return bills.toArray(new AggCenterVO[0])[0];
  }

  /**
   * 判断新增或修改
   *
   * @param vo
   */
  private void doBefore(AggCenterVO vo) {
    String parentPk = vo.getPrimaryKey();

    CenterVO hvo = vo.getParentVO();
    //所属组织
    String pk_org = hvo.getPk_org();
    //单据日期
    UFDate ufDate = hvo.getDbilldate();
    int year = ufDate.getYear();
    String yearm = year+"-";
    int month = ufDate.getMonth();
    if(month<10) {
    	yearm = yearm + "0"+month;
    }else {
    	yearm =yearm+month;
    }
    IUAPQueryBS find = ServiceLocator.find(IUAPQueryBS.class);
    //查询核算账簿
    String sql = "select a.isendacc from org_closeacc a left join bd_accperiodmonth b on a.pk_accperiodmonth = b.pk_accperiodmonth where a.moduleid = '2002' and a.pk_org = '"+pk_org+"' and b.yearmth = '"+yearm+"'";
	try {
		String isendacc = (String) find.executeQuery(sql, new ColumnProcessor());
		if(!StringUtils.isBlank(isendacc) && "Y".equals(isendacc)) {
			ExceptionUtils.wrapBusinessException("对应会计期间已关账");
		}
	} catch (BusinessException e) {
		e.printStackTrace();
		ExceptionUtils.wrapBusinessException(e.getMessage());
	}
    
    CircularlyAccessibleValueObject[] bvos = vo.getChildrenVO();
    if(bvos.length==0) {
    	ExceptionUtils.wrapBusinessException("表体数据为空，不允许保存");
    }
    for(int i=0;i<bvos.length;i++) {
    	CenterBVO bvo = (CenterBVO) bvos[i];
    	//行号
    	String rowno = bvo.getRowno();
    	//客商
    	String cussup = bvo.getCussup();
    	//业务类型
    	String def5 = bvo.getDef5();
    	if(!StringUtils.isBlank(cussup)) {
    		checkFile(def5,rowno,"业务类型");
    	}
    	//交易类型
    	String def6 = bvo.getDef6();
    	//cp单号
    	String cpid = bvo.getCpid();
    	//下单利润中心
    	String ordercenter = bvo.getOrdercenter();
    	//付款利润中心
    	String paycenter = bvo.getPaycenter();
    	//费用承担部门
    	String def1 = bvo.getDef1();
    	//报销类型
    	String def2 = bvo.getDef2();
    	//费用明细
    	String def3 = bvo.getDef3();
    	//车牌号
    	String def7 = bvo.getDef7();
    	//调整类型
    	String def9 = bvo.getDef9();
    	if(!StringUtils.isBlank(def9)) {
    		String code = queryDoc(def9,find);
    		if("01".equals(code) || "02".equals(code) || "03".equals(code) || "04".equals(code) || "07".equals(code) || "08".equals(code) || "09".equals(code) || "10".equals(code)) {
    			//客商编码、业务类型、交易类型、CP单号、下单利润中心
    			checkFile(cussup,rowno,"客商编码");
    			checkFile(def5,rowno,"业务类型");
    			checkFile(def6,rowno,"交易类型");
    			checkFile(cpid,rowno,"CP单号");
    			checkFile(ordercenter,rowno,"下单利润中心");
    		}else if("05".equals(code) || "06".equals(code) || "11".equals(code) || "12".equals(code) || "13".equals(code) || "14".equals(code) || "15".equals(code) || "19".equals(code)) {
    			//费用承担部门、报销类型、费用明细、车牌号
    			checkFile(def1,rowno,"费用承担部门");
    			checkFile(def2,rowno,"报销类型");
    			checkFile(def3,rowno,"费用明细");
    			if("05".equals(code) || "11".equals(code)) {
    				checkFile(def7,rowno,"车牌号");
    			}
    		}
    	}
    	if(!StringUtils.isBlank(def6)) {
    		String code = queryDoc(def6,find);
    		if("DI".equals(code)) {
    			checkFile(paycenter,rowno,"付款利润中心");
    		}
    	}
    }
    
    // 根据是否有主键信息判断是新增保存还是修改保存
    if ((parentPk != null) && !"".equals(parentPk)) {
      // 设置单据默认值
      CircularlyAccessibleValueObject[] allchildren = vo.getAllChildrenVO();
      if (allchildren != null) {
        for (CircularlyAccessibleValueObject obj : allchildren) {
          obj.setAttributeValue("pk_lrcenter_h", parentPk);
        }
      }
    }
  }

  private void checkFile(String pk, String rowno, String name) {
	  if(StringUtils.isBlank(pk)) {
		  ExceptionUtils.wrapBusinessException("行号："+rowno+"，"+name+"不能为空");
  	  }
  }

private String queryDoc(String pk, IUAPQueryBS find) {
	String qsql = "select code from bd_defdoc where pk_defdoc = '"+pk+"'";
	try {
		String code = (String) find.executeQuery(qsql, new ColumnProcessor());
		return code;
	} catch (BusinessException e) {
		e.printStackTrace();
		ExceptionUtils.wrapBusinessException(e.getMessage());
	}
	return "";
  }
}
